<?php

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
 	require_once (APPLICATION_PATH . "\\models\\connectionDb.php");
	require_once (APPLICATION_PATH . "\\functions\\utilities.php");
} else {
        require_once (APPLICATION_PATH . "//models//connectionDb.php");
	require_once (APPLICATION_PATH . "//functions//utilities.php");
}

class LoginController extends Zend_Controller_Action
{

    public function init()
    {
        $this->_helper->layout()->setLayout('loginlayout');
    }

    public function indexAction()
    {
       	$form_login = new Application_Form_Login();
       	$this->view->form_login = $form_login;
       	
       	if($this->getRequest()->isPost()){
       		$form_login_Data = $this->getRequest()->getPost();
       		if ($form_login->isValid($form_login_Data)){
       			
       			$email = $form_login->getValue("txt_email");
       			$password = $form_login->getValue("txt_password");

       		       			
       			//getting the connection the Database
       			$db = connectionDb::connectDB();       			
       			
       			//authentication using Zend_Auth class on Database level
       			$authAdapter = new Zend_Auth_Adapter_DbTable($db);			
       			
				$authAdapter->setTableName('Users')
    						->setIdentityColumn('Email')
    						->setCredentialColumn('Password');
    			
    			//binding the credentials to the adapter    			
    			$authAdapter->setIdentity($email)
    						->setCredential($password);
    		    
    						
    			$auth = Zend_Auth::getInstance();
        		$result = $auth->authenticate($authAdapter);		
       			
        		if ($result->isValid()){
        			       			
        			$users_BO = new Application_Model_DbTable_Users();
        			//fetch the user from the Buss Object        			
        			$user = $users_BO->getUserLogin($email, $password);
        		        		
        			
        			
        			// finta ss token da se primeni
        			if ($user['Token'] == 0) {
        				$token = $this->_request->getQuery("token");
        				if (empty($token)) {
        					echo "Please check your email for activation link and try again";
        					//$this->_helper->redirector('index','login');
        				}
        				else{
        					
        					$token_BO = new Application_Model_DbTable_Token();
        					$token_user = $token_BO->getToken($email);
        					
        					
        					if ($token_user == null){
        						echo "Invalid Email";        					
        					}
        					else
        					{
        						if ($token_user['Token'] ==$token)
        						{        							
        							$users_BO->editUserToken($user['id']);
        							$user = $users_BO->getUserLogin($email, $password);
        							
        							$InterestInfo_BO = new Application_Model_DbTable_Interestinfo();        							
        							$InterestInfo_BO->createInterestInfo($user['id'], 0);
        							$Interest = $InterestInfo_BO->getInterestInfo($user['id']);
        							
        							$BasicInfo_BO = new Application_Model_DbTable_Basicinfo();
        							$BasicInfo_BO->createBasicInfo($user['id'], 0);
        							$BasicInfo = $BasicInfo_BO->getBasicInfo($user['id']);
        							
        							$MedicalInfo_BO =  new Application_Model_DbTable_Medicalinfo();
        							$MedicalInfo_BO->createMedicalInfo($user['id'], 0);
        							$MedicalInfo = $MedicalInfo_BO->getMedicalInfo($user['id']);
        							
        							//dodavanje na sam sebe kako prijatel
        							//$Friend_BO =  new Application_Model_DbTable_Friends();
        							//$Friend_BO->addSelfAsFriend($user['id']);
        							
        							$users_BO->addBasicInfo($user['id'],$BasicInfo['id']);
        							$users_BO->addInterestInfo($user['id'], $Interest['id']);
        							$users_BO->addMedicalInfo($user['id'], $MedicalInfo['id']);
        							        							
	        						$session = Zend_Registry::get('session');
									$session->user=$user;				
									
									//Vreme kolku da trae sesijata;
									//$session->setExpirationSeconds(12000);
									//Da se zatvori sesijata ako se vece uspesno logirame;
									$session->lock();
																	
									
									//echo $session->user['Password'];
				        			
									//Redirektiranje kon main ako e uspesno logiranjeto					
									$this->_helper->redirector('index','home');
        						
        						}
        						else{
        							echo "Invalid Activation link";
        						}         						
        					}   
        				}        		
        			}
        			else{  			
        			
	        			$session = Zend_Registry::get('session');
						$session->user=$user;				
						
						//Vreme kolku da trae sesijata;
						//$session->setExpirationSeconds(12000);
						//Da se zatvori sesijata ako se vece uspesno logirame;
						$session->lock();								
						
						//echo $session->user['Password'];
	        			
						//Redirektiranje kon main ako e uspesno logiranjeto					
						$this->_helper->redirector('index','home');
        			}
        		}
        		else{
        			//Set the error message and re-display the login page.
        			/*echo "Incorrect Email or Password, please retype them";
        			$this->view->form_login = $form_login; //da se pokaze formata povtorno
					$this->render("Index");    */
					
        			$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
					$redirector->gotoUrl('/errinfo/loginerr');       			
        		}
        		
       		}
       		else
       		{       			
       			$this->view->form_login = $form_login;
				$this->render("Index");       		
       		} 
       			
    	
    }
    }

    public function registrationAction()
    {
        $form_registration = new Application_Form_Registration();
        $this->view->form_registration = $form_registration;
        $users = new Application_Model_DbTable_Users();
        
        if($this->getRequest()->isPost()){
        	$form_registration_Data = $this->getRequest()->getPost();
        	if ($form_registration->isValid($form_registration_Data)){
        		
        		$username=$form_registration->getValue('txt_username');
        		$password=$form_registration->getValue('txt_password');
        		$password_confirm=$form_registration->getValue('txt_password_confirm');
        		$email=$form_registration->getValue('txt_email');
        		$usertype =$form_registration->getValue('cmb_type_user');
        		//echo $username;
        		
	        	if($password==$password_confirm)
				{
					$exist = $users->getUserByEmailOrUsername($email,$username);
					
					if ($exist == null) {	
						
						//$filename  = APPLICATION_PATH . "\Users\$email\";		
						//mkdir($filename);					
			
						//generate Token for the User so he can login for the first time, 
						//way to check that he will use the social network and that mail is valid and used in real world
						$token = utilities::make_token(25);

						//make the url link to login page including the token in query						
						$link_url = "http://localhost/med-advisor/public/Login?token=".$token;
						
						// send email to the user						
						$mail_Message = "In order to come part of this comunity please folow the link and login ".$link_url;
						$mail_Type = "1";
						$mail_Subject=  "One step for joining Med-Advisor";	
										
						utilities::smtpSendMailAction($email,$mail_Message,$mail_Type,$mail_Subject);
											
						$users->addUser($email, $password, $usertype, $username, '1','');						
						$token_table = new Application_Model_DbTable_Token();						
						$token_table->createToken($email, $token);
						
						$this->_helper->redirector('index');
					}
					else{
						echo "Already exist user with that Email or Username";					
					}
				}
						//dodaten if uslov za da se proveri dali e unique username i password i vlecenje od bazata
				else
				{					
					echo "The passwords dont match";
					$form_registration->populate($form_registration_Data);
				}	        		
	        }
    	
    }
    }
    public function logoutAction()
    {
    	try{
	        $session = Zend_Registry::get('session');
			$session->unsetAll();
			$this->_helper->redirector('index');
    	}
    	catch (Zend_Exception $e) {  
			echo "Error message: " . $e->getMessage() . "\n";
        } 	
    }
    


}





